package com.vuej.core;

import com.vuej.entity.VueFile;
import com.vuej.exception.VuejException;

import com.vuej.util.VueFileRenderCallbackWrapper;
import com.vuej.util.VueUtil;

import javax.script.Invocable;
import javax.script.ScriptException;
import java.io.IOException;

public class DefaultVueRender implements VueRender {


    @Override
    public void init(ScriptEnvironment environment) throws IOException, ScriptException {
        environment.evalClassLib("lib/defaultRender.js");
    }

    @Override
    public void render(ScriptEnvironment environment, VueFile file, VueFileRenderCallback callback) throws Throwable {
        Invocable invocable = (Invocable)environment.getEngine();
        //引入wrapper,修复有时候当发生Throwable时，抛出Cannot cast xxx to javax.script.Bindings
        VueFileRenderCallbackWrapper wrapper = new VueFileRenderCallbackWrapper(callback);
        try{
            invocable.invokeFunction("renderApp", file, wrapper);
        }catch (ClassCastException e){
            if("Cannot cast com.vuej.exception.VuejException to javax.script.Bindings".equals(e.getMessage())){
                throw wrapper.getThrowableThreadLocal().get().getCause();
            }
        }finally {
            wrapper.getThrowableThreadLocal().remove();
        }
    }
}
